﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Web.Routing;

namespace MvcTemplates
{
    public static class ModelMetadataExtensions
    {
        public static bool HasTemplateData<T>( this ModelMetadata modelMetadata )
            where T : MetadataAttribute
        {
            return modelMetadata.AdditionalValues.ContainsKey( typeof ( T ).Name );
        }
        public static T GetTemplateData<T>( this ModelMetadata modelMetadata )
            where T : MetadataAttribute
        {
            return modelMetadata.GetTemplateData( typeof ( T ) ) as T;
        }
        public static object GetTemplateData( this ModelMetadata modelMetadata, Type metaDataAttributeType )
        {
            if ( modelMetadata.AdditionalValues.ContainsKey( metaDataAttributeType.Name ) )
                return modelMetadata.AdditionalValues[metaDataAttributeType.Name];
            return null;
        }

        public static IDictionary<string, object> MergeAttributes( this ModelMetadata modelMetadata, object attributes, Type metaDataAttributeType )
        {
            var rvd = new RouteValueDictionary( attributes );

            var templateData = (HtmlAttributesAttribute) modelMetadata.GetTemplateData( metaDataAttributeType );
            
            if ( templateData == null )
                return rvd;

            templateData.ModifyHtmlAttributes( rvd );

            return rvd;
        }

        public static IDictionary<string, object> MergeAttributes<TAttribute>( this ModelMetadata modelMetadata, object attributes )
            where TAttribute : HtmlAttributesAttribute
        {
            return modelMetadata.MergeAttributes( attributes, typeof ( TAttribute ) );
        }
    }
}